<?php
/**
 * Created by PhpStorm.
 * User: jiankian
 * Date: 2017/4/8
 * Time: 上午10:06
 */
namespace app\expbao\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\expbao\model\ExRules as RuleModel;
use think\Db;
class Rules extends Admin{

    public function index(){
    	$map = $this->getMap();
       // $aaa=RuleModel::alias(['dp_expbao_rules'=>'rules','dp_expbao_group'=>'group'])->join('dp_expbao_rules','rules.gid = group.id')->select();
        $data_list = RuleModel::table('__EXPBAO_RULES__')
            ->alias('t1')
            ->field('t1.*,t2.group')
            ->join('expbao_group t2','t1.gid = t2.id','LEFT')
            ->paginate();
    	//$aaa = RuleModel::join('expbao_group ON expbao_rules.gid = expbao_group.id' );
    	//$aaa=RuleModel::get(1);
    	//var_dump($aaa);
    	//echo $aaa->func;
    	 $page = $data_list->render();
    	return ZBuilder::make('table')
            ->setPageTitle('规则管理') // 设置页面标题
            ->setTableName('expbao_rules') // 设置数据表名
            ->setSearch(['id' => 'ID', 'func' => '规则名']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['func_name', '规则名'],
                ['func', '规则方法'],
                ['gid', '规则组ID'],
                ['group', '规则组名'],
                ['create_time', '添加时间', 'datetime'],
                ['state', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setPrimaryKey('id') // 设置主键名为username
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
        return $this->fetch();
    }
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            
            $result = $this->validate($data, 'ExRule');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            if ($rule = RuleModel::create($data)) {
                // 记录行为
                //action_log('member_add', 'member', $rule['id'], UID);
                return $this->success('新增成功', url('index'));
            } else {
                return $this->error('新增失败');
            }
        }
$group_list = Db::table('__EXPBAO_GROUP__')->field('id,group')->where('1=1')->select();
$group_lists=array_column($group_list,'group','id');
        // 使用TKuitpl快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增规则') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'func_name', '规则名', '必填，可由中文英文数字组成'],
                ['text', 'func', '规则方法', '必填，可由英文字母、数字组成'],
                ['select', 'gid', '规则组名', '请选择一个规则组',$group_lists,'group'],
                ['radio', 'state', '状态', '', ['禁用', '启用'], 1]
            ])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 用户id
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) return $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();



            // 验证
            $result = $this->validate($data, 'ExRule.update');
            // 验证失败 输出错误信息
            if(true !== $result) return $this->error($result);

            // 如果没有填写密码，则不更新密码
            //if ($data['member_passwd'] == '') {
              //  unset($data['member_passwd']);
           // }

            if ($user = RuleModel::update($data)) {
                // 记录行为
                //action_log('user_edit', 'member_user', $user['id'], UID, get_nickname($user['id']));
                return $this->success('编辑成功', cookie('__forward__'));
            } else {
                return $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = RuleModel::where('id', $id)->field('member_passwd', true)->find();

        // 使用TKuitpl快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['text', 'func_name', '方法名称', '可以是中文'],
                ['text', 'func', '方法名', ''],
                ['select', 'gid', '规则组名', '请选择一个规则组',$group_lists,'group'],
                ['radio', 'member_state', '状态', '', ['禁用', '启用']]
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 授权
     * @param string $tab tab分组名
     * @param int $uid 用户id
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function access($tab = '', $uid = 0)
    {
        if ($uid === 0) return $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $post = $this->request->post();
            list($module, $group) = explode('_', $post['tab_name']);

            // 先删除原有授权
            $map['module'] = $module;
            $map['group']  = $group;
            $map['uid']    = $post['uid'];
            if (false === AccessModel::where($map)->delete()) {
                return $this->error('清除旧授权失败');
            }

            $data = [];
            // 授权节点
            $nids = [];
            if (isset($post['group_auth'])) {
                $nids = $post['group_auth'];
                foreach ($post['group_auth'] as $nid) {
                    $data[] = [
                        'nid'    => $nid,
                        'uid'    => $post['uid'],
                        'group'  => $group,
                        'module' => $module
                    ];
                }
                // 添加新的授权
                $AccessModel = new AccessModel;
                if (!$AccessModel->saveAll($data)) {
                    return $this->error('操作失败');
                }
            }

            // 记录行为
            $nids = !empty($nids) ? implode(',', $nids) : '无';
            $details = "模块($module)，分组($group)，授权节点ID($nids)";
            action_log('user_access', 'admin_user', $uid, UID, $details);
            return $this->success('操作成功', 'index');
        }

        // 获取所有授权配置信息
        $list_access = ModuleModel::where('access', 'neq', '')->column('access', 'name');
        if ($list_access) {
            $curr_access  = '';
            $group_table  = '';
            $tab_list     = [];
            foreach ($list_access as $module => &$groups) {
                $groups = json_decode($groups, true);

                foreach ($groups as $group => $access) {
                    // 如果分组为空，则默认为第一个
                    if ($tab == '') {
                        // 当前分组名
                        $tab = $module. '_' . $group;
                        // 节点表名
                        $group_table = $access['table_name'];
                        // 当前权限配置信息
                        $curr_access = $access;
                    }

                    // 配置分组信息
                    $tab_list[$module. '_' . $group] = [
                        'title' => $access['tab_title'],
                        'url'   => url('access', [
                            'tab' => $module. '_' . $group,
                            'uid' => $uid
                        ])
                    ];
                }
            }

            list($module, $group) = explode('_', $tab);
            if ($curr_access == '') {
                $curr_access = $list_access[$module][$group];
                $group_table = $curr_access['table_name'];
            }

            // tab分组信息
            $tab_nav = [
                'tab_list' => $tab_list,
                'curr_tab' => $tab
            ];
            $this->assign('tab_nav', $tab_nav);

            // 获取授权数据
            $groups = '';
            if (isset($curr_access['model_name']) && $curr_access['model_name'] != '') {
                $class = "app\\{$module}\\model\\".$curr_access['model_name'];
                $model = new $class;

                try{
                    $groups = $model->access();
                }catch(\Exception $e){
                    $this->error('模型：'.$class."缺少“access”方法");
                }
            } else {
                // 没有设置模型名，则按表名获取数据
                $fileds = [
                    $curr_access['primary_key'],
                    $curr_access['parent_id'],
                    $curr_access['node_name']
                ];

                $groups = Db::name($group_table)->order($curr_access['primary_key'])->field($fileds)->select();
            }

            if ($groups) {
                // 查询当前用户的权限
                $map['module'] = $module;
                $map['group']  = $group;
                $map['uid']    = $uid;
                $node_access = AccessModel::where($map)->column('nid');
                $this->assign('node_access', $node_access);
                $this->assign('tab_name', $tab);
                $this->assign('field_access', $curr_access);
                $tree_config = [
                    'title' => $curr_access['node_name'],
                    'id'    => $curr_access['primary_key'],
                    'pid'   => $curr_access['parent_id']
                ];
                $this->assign('groups', Tree::config($tree_config)->toList($groups));
            }
        }

        $this->assign('page_title', '数据授权');
        return $this->fetch();
    }

    /**
     * 删除用户
     * @param array $record 行为日志
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用用户
     * @param array $record 行为日志
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用用户
     * @param array $record 行为日志
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置用户状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $uid_delete = is_array($ids) ? '' : $ids;
        $ids        = array_map('get_nickname', (array)$ids);
        return parent::setStatus($type, ['user_'.$type, 'member_user', $uid_delete, UID, implode('、', $ids)]);
        
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
        $config  = RuleModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
        return parent::quickEdit(['user_edit', 'member_user', $id, UID, $details]);
    }
}